<template>
  <a-modal width="50%" :bodyStyle="{ height: '550px', overflow: 'auto' }" v-model="isModel" :title="labelTitle">
    <a-form-model
      ref="thirdPersonFormRef"
      :rules="rules"
      style="width: 100%"
      labelAlign="left"
      :model="thirdPersonForm"
    >
      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="第三人类型" prop="type" has-feedback>
          <a-select allow-clear placeholder="请选择第三人类型" v-model="thirdPersonForm.type" @change="changePersonType">
            <a-select-option v-for="item in Tp_applicant" :key="item.value">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="thirdPersonForm.type == Tp_applicantValue.CITIZEN ? '姓名':'名称'" prop="name" has-feedback>
          <a-input v-model="thirdPersonForm.name" allow-clear :maxLength="125" :placeholder="thirdPersonForm.type == Tp_applicantValue.CITIZEN ? '请输入姓名':'请输入名称'" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="thirdPersonForm.type == Tp_applicantValue.CITIZEN">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="证件类型"
          prop="cardtype"
          has-feedback
        >
          <a-select allow-clear placeholder="请选择证件类型" v-model="thirdPersonForm.cardtype">
            <a-select-option v-for="item in Tp_card" :key="item.id">
              {{ item.description }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :label="thirdPersonForm.type == Tp_applicantValue.UNIT ? '统一信用代码':'证件号'"
          prop="cardno">
          <a-input
            v-model="thirdPersonForm.cardno"
            allow-clear
            :maxLength="125"
            :placeholder="thirdPersonForm.type == Tp_applicantValue.UNIT ? '请输入统一信用代码':'请输入证件号'" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="thirdPersonForm.type == Tp_applicantValue.CITIZEN">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="性别"
          prop="gender"
        >
          <a-select allow-clear placeholder="请选择性别" v-model="thirdPersonForm.gender">
            <a-select-option v-for="item in Tp_gender" :key="item.id">
              {{ item.description }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>

      <!-- 公民显示字段 -->
      <a-col :xxl="12" :lg="12" :sm="24" v-if="thirdPersonForm.type == Tp_applicantValue.CITIZEN">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="民族"
          prop="nation"
        >
          <a-select allow-clear placeholder="请选择民族" v-model="thirdPersonForm.nation">
            <a-select-option v-for="item in Tp_nation" :key="item.id">
              {{ item.description }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="thirdPersonForm.type == Tp_applicantValue.CITIZEN">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="出生年月"
          prop="birthym"
        >
          <a-date-picker
            v-model="thirdPersonForm.birthym"
            placeholder="请选择出生年月"
            format="YYYY-MM-DD"
            :allowClear="true"
          />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="联系电话" prop="tel">
          <a-input v-model="thirdPersonForm.tel" allow-clear :maxLength="125" placeholder="请输入联系电话" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="联系地址" prop="addr">
          <a-input v-model="thirdPersonForm.addr" allow-clear :maxLength="125" placeholder="请输入联系地址" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="邮政编码" prop="postcode">
          <a-input v-model="thirdPersonForm.postcode" allow-clear :maxLength="125" placeholder="请输入邮政编码" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="thirdPersonForm.type == Tp_applicantValue.CITIZEN">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="工作单位"
          prop="unit"
        >
          <a-input v-model="thirdPersonForm.unit" allow-clear :maxLength="125" placeholder="请输入工作单位" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="thirdPersonForm.type == Tp_applicantValue.CITIZEN">
        <a-form-model-item
          label="身份证明"
          prop="filecard"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <!-- :customRequest="(file) => uploadFile(file, 1)"
            :remove="(file) => removeFile(file, 1)"
            :before-upload="(file) => beforeUpload(file, 1)" -->
          <a-upload
            :accept="acceptFileType"
            :file-list="filecardList"
            :remove="(file) => removeFile(file, 0)"
            name="file"
            :multiple="true"
          >
            <a-button icon="upload" @click.stop="uploadFile(0)"> 上传 </a-button>
          </a-upload>
        </a-form-model-item>
      </a-col>

      <!-- 法人显示字段 -->
      <a-col :xxl="12" :lg="12" :sm="24" v-if="thirdPersonForm.type == Tp_applicantValue.UNIT">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="法定代表人"
          prop="manager"
          has-feedback
        >
          <a-input v-model="thirdPersonForm.manager" allow-clear :maxLength="125" placeholder="请输入法定代表人" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="thirdPersonForm.type == Tp_applicantValue.UNIT">
        <a-form-model-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="工作"
          prop="job"
        >
          <a-input v-model="thirdPersonForm.job" allow-clear :maxLength="125" placeholder="请输入工作" />
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24" v-if="thirdPersonForm.type == Tp_applicantValue.UNIT">
        <a-form-model-item
          label="身份证明书"
          prop="doccard"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <!-- :customRequest="(file) => uploadFile(file, 2)"
            :remove="(file) => removeFile(file, 2)"
            :before-upload="(file) => beforeUpload(file, 2)" -->
          <a-upload
            :accept="acceptFileType"
            :file-list="doccardList"
            :remove="(file) => removeFile(file, 1)"
            name="file"
            :multiple="true"
          >
            <a-button icon="upload" @click.stop="uploadFile(1)"> 上传 </a-button>
          </a-upload>
        </a-form-model-item>
      </a-col>

      <a-col :xxl="12" :lg="12" :sm="24">
        <a-form-model-item
          label="第三人证据材料"
          prop="thirdevidence"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <!-- :customRequest="(file) => uploadFile(file, 2)"
            :remove="(file) => removeFile(file, 2)"
            :before-upload="(file) => beforeUpload(file, 2)" -->
          <a-upload
            :accept="acceptFileType"
            :file-list="thirdEvidenceList"
            :remove="(file) => removeFile(file, 2)"
            name="file"
            :multiple="true"
          >
            <a-button icon="upload" @click.stop="uploadFile(2)"> 上传</a-button>
          </a-upload>
        </a-form-model-item>
      </a-col>

    </a-form-model>

    <MultiUploadBasic ref="multiUploadBasic" @importFileFun="importFileFun"></MultiUploadBasic>
    <template slot="footer">
      <div style="display: flex; justify-content: center">
        <a-button class="m-r-8" icon="cancel" @click="onClose"> 取消 </a-button>
        <a-button
          class="m-r-8"
          type="primary"
          @click="onSubmit"
          icon="save"
          :loading="loading"
          v-if="applyid != ''">
          保存
        </a-button>
      </div>
    </template>
  </a-modal>
</template>

<script>
import { Tp_applicantList, Tp_applicantValue } from '@/enumeration/Tp_applicant'
import { nanoid } from 'nanoid'
import { minioUpload, minioRemove, minioUploadMore } from '@/api/base/file'
import { saveThirdPerson } from '@/api/accept/apl_thirdper'
import { queryEnumeration } from '@/api/accept/enum_load'
import { getSexByIdCard, getAge, getBirthday } from '@/utils/idCard.js'
import { Tp_genderValue } from '@/enumeration/Tp_gender.js'
import { FILETYPE, FILESIZE } from '@/store/mutation-types'
import { saveMaterialRepeat } from '@/api/accept/aprv_process_materials'
import { Tp_procmaterialValue } from '@/enumeration/Tp_procmaterial'
import { Tp_proctypeValue } from '@/enumeration/Tp_proctype'
import { APP_USER } from '@/store/mutation-types.js'
import storage from 'store'
export default {
  props: {
    applyid: {
      // 申请id
      type: String,
      required: true
    }
  },
  data () {
    return {
      labelCol: { span: 6 }, // label宽
      wrapperCol: { span: 16 }, // 组件宽
      loading: false, // 按钮显示
      isModel: false, // 模态框显示
      Tp_applicant: Tp_applicantList, // 第三人类型
      Tp_applicantValue: Tp_applicantValue,
      Tp_card: [], // 证件类型
      Tp_gender: [], // 性别
      Tp_nation: [], // 民族
      thirdPersonForm: {
        id: '', // id
        applyid: '', // applyid
        type: undefined, // 第三人类型
        name: '', // 名称
        gender: undefined, // 性别
        nation: undefined, // 民族
        birthym: undefined, // 出生日期
        cardtype: undefined, // 证件类型
        cardno: '', // 证件号
        tel: '', // 联系号码
        manager: '', // 法定责任人
        postcode: '', // 邮政编码
        addr: '', // 地址
        job: '', // 职务
        unit: '', // 工作单位
        filecard: '', // 身份证明
        doccard: '', // 身份证明书
        thirdevidence: '' // 第三人证据材料
      },
      filecardList: [], // 身份证明文件
      doccardList: [], // 身份证明书文件
      thirdEvidenceList: [], // 第三人证据材料
      deleteFileList: [], // 删除的文件列表
      selectType: '',
      /**
       * 添加表单验证规则
       */
      rules: {
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        cardno: [{ validator: this.checkCardno }],
        tel: [{ validator: this.checkTel }],
        postcode: [{ validator: this.checkPostcode }]
      },
      labelTitle: '',
      acceptFileType: FILETYPE,
      operateType: undefined,
      Tp_procmaterialValue: Tp_procmaterialValue,
      Tp_proctypeValue: Tp_proctypeValue,
      currentUser: storage.get(APP_USER)
    }
  },
  components: {
    MultiUploadBasic: () => import('@/views/materials/multiUpload/MultiUploadBasic.vue')
  },
  created () {
    this.queryEnumeration('Tp_card', (val) => {
      this.Tp_card = val
    })
    this.queryEnumeration('Tp_gender', (val) => {
      this.Tp_gender = val
    })
    this.queryEnumeration('Tp_nation', (val) => {
      this.Tp_nation = val
    })
  },
  watch: {
    'thirdPersonForm.cardno': {
      handler: function (newVal, oldVal) {
        // 当前的类型是公民类型
        if (this.thirdPersonForm.type == this.Tp_applicantValue.CITIZEN) {
          if (newVal && /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(newVal)) {
            // 通过身份证计算对应的年龄和性别
            const sex = getSexByIdCard(newVal)
            const age = getAge(newVal)
            const birth = getBirthday(newVal)
            this.thirdPersonForm.gender = sex == 1 ? Tp_genderValue.MALE : Tp_genderValue.FEMALE
            this.thirdPersonForm.birthym = birth
          }
        }
      },
      deep: true
    }
  },

  methods: {
    init (isEdit, editForm) {
      this.isModel = true
      if (isEdit) {
        this.labelTitle = '编辑第三人'
        this.resetFileList()
        this.thirdPersonForm = Object.assign({}, this.thirdPersonForm, editForm)
        if (editForm.filecardList != null && editForm.filecardList != undefined) {
          editForm.filecardList.forEach(item => {
            const file = {
              uid: item.id,
              name: item.filename,
              status: 'done',
              url: item.path,
              flag: item.id
            }
            this.filecardList.push(file)
          })
        }
        if (editForm.doccardList != null && editForm.doccardList != undefined) {
          editForm.doccardList.forEach(item => {
            const file = {
              uid: item.id,
              name: item.filename,
              status: 'done',
              url: item.path,
              flag: item.id
            }
            this.doccardList.push(file)
          })
        }
        if (editForm.thirdEvidenceList != null && editForm.thirdEvidenceList != undefined) {
          editForm.thirdEvidenceList.forEach(item => {
            const file = {
              uid: item.id,
              name: item.filename,
              status: 'done',
              url: item.path,
              flag: item.id
            }
            this.thirdEvidenceList.push(file)
          })
        }
      } else {
        this.labelTitle = '新增第三人'
        this.thirdPersonForm = {
          id: '', // id
          applyid: '', // applyid
          type: undefined, // 第三人类型
          name: '', // 名称
          gender: undefined, // 性别
          nation: undefined, // 民族
          birthym: undefined, // 出生日期
          cardtype: undefined, // 证件类型
          cardno: '', // 证件号
          tel: '', // 联系号码
          manager: '', // 法定责任人
          postcode: '', // 邮政编码
          addr: '', // 地址
          job: '', // 职务
          unit: '', // 工作单位
          filecard: '', // 身份证明
          doccard: '', // 身份证明书
          thirdevidence: '' // 第三人证据材料
        }
        this.resetFileList()
      }
      this.thirdPersonForm.applyid = this.applyid
      if (this.applyid == '' || this.applyid == undefined) {
        this.$message.error('当前传入的applyid为空, 无法正常新增')
        this.isModel = false
      }
    },
    /**
     * 查询枚举值
     */
    async queryEnumeration (val, callback) {
      await queryEnumeration({ 'enName': val }).then((res) => {
        if (res.code !== 0) {
          console.log('查询枚举值错误')
        } else {
          callback(res.data)
        }
      })
    },
    checkCardno (rule, value, callback) {
      if (value && !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
        callback(new Error('证件号码不正确'))
      }
      callback()
    },
    checkTel (rule, value, callback) {
      if (value && !/^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/.test(value)) {
        callback(new Error('联系号码不正确'))
      }
      callback()
    },
    checkPostcode (rule, value, callback) {
      if (value && !/^[0-9]{6}$/.test(value)) {
        callback(new Error('邮政编码不正确'))
      }
      callback()
    },

    /**
     * 关闭页面
     */
    onClose () {
      this.resetForm()
      this.isModel = false
    },
    resetFileList () {
      this.filecardList = [] // 身份证明文件
      this.doccardList = [] // 身份证明书文件
      this.thirdEvidenceList = []
    },
    /**
     * 重置表单
     */
    resetForm () {
      console.log('form', this.$refs.thirdPersonFormRef)
      this.resetFileList()
    },
    getNanoId () {
      return nanoid()
    },
    removeFile (file, type) {
      if (type === 0) {
        this.filecardList = this.filecardList.filter((item) => item.uid !== file.uid)
      } else if (type === 1) {
        this.doccardList = this.doccardList.filter((item) => item.uid !== file.uid)
      } else if (type === 2) {
        this.thirdEvidenceList = this.thirdEvidenceList.filter((item) => item.uid !== file.uid)
      }
      this.deleteFileList.push(file.uid)
    },
    minioRemove (fileId) {
      minioRemove({ 'fileid': fileId }).then((res) => {
        console.log('res', res)
        if (res.code !== 0) {
          console.log('删除文件失败', res)
        } else {
          console.log('删除文件成功', fileId)
        }
      })
    },
    // 上传附件
    uploadFile (operateType) {
      // this.selectData = record
      this.operateType = operateType
      this.$refs.multiUploadBasic.importVisible = true
    },
    /**
     * 确定保存导入数据
     */
    importFileFun (importFileList) {
      let _this = this
      console.log('importFileList', importFileList)
      const files = []
      importFileList.forEach((item) => {
        files.push(item)
      })
      this.$refs.multiUploadBasic.loading = true
      if (this.operateType == null || this.operateType == undefined) {
        this.$message.error('操作类型为空')
      }
      if (this.operateType == 0 || this.operateType == 1) {
        minioUploadMore(files).then((res) => {
          if (res.code == 0) {
            const attachs = res.data
            attachs.forEach((attach) => {
              const file = {
                uid: attach.id,
                name: attach.filename,
                status: 'done',
                url: attach.url,
                flag: attach.id
              }
              if (this.operateType === 0) {
                _this.filecardList.push(file)
              } else {
                _this.doccardList.push(file)
              }
            })
            this.$message.success('上传成功')
            this.$refs.multiUploadBasic.handleCancel()
          } else {
            this.$message.success('上传失败')
            this.$refs.multiUploadBasic.handleCancel()
          }
        }).finally(() => {
          this.$refs.multiUploadBasic.loading = false
        })
      } else if (this.operateType == 2) {
        const param = {
          applyid: this.applyid,
          fileType: this.Tp_procmaterialValue.MATER_INVENTORY,
          busiType: this.Tp_proctypeValue.ACCEPT_ACCEPT,
          userId: this.currentUser.userId,
          userName: this.currentUser.fullname
        }
        saveMaterialRepeat(param, importFileList)
          .then(res => {
            if (res.code !== 0) {
              this.$message.success('上传失败')
              this.$refs.multiUploadBasic.handleCancel()
            } else {
                const attachs = res.data
                attachs.forEach((attach) => {
                  if (attach && attach.file) {
                    const file = {
                      uid: attach.file.id,
                      name: attach.file.filename,
                      status: 'done',
                      url: attach.file.path,
                      flag: attach.file.id
                    }
                    this.thirdEvidenceList.push(file)
                  }
                })
                this.$message.success('上传成功')
                this.$refs.multiUploadBasic.handleCancel()
            }
          })
          .catch(err => {
            console.log(err, '上传数据失败')
          })
          .finally(() => {
            this.$refs.multiUploadBasic.loading = false
          })
      }
    },

    /**
     * 提交表单
     */
    onSubmit () {
      const _this = this
      // copyForm. = unitTypeList.filter
      this.$refs.thirdPersonFormRef.validate((valid) => {
        _this.loading = true
        if (valid) {
          if (_this.filecardList != null && _this.filecardList.length > 0) {
            const uploadFile = []
            _this.filecardList.forEach((item) => {
              uploadFile.push(item.uid)
            })
            _this.thirdPersonForm.filecard = uploadFile.join(',')
          } else {
            _this.thirdPersonForm.filecard = ''
          }
          if (_this.doccardList != null && _this.doccardList.length > 0) {
            const uploadFile = []
            _this.doccardList.forEach((item) => {
              uploadFile.push(item.uid)
            })
            _this.thirdPersonForm.doccard = uploadFile.join(',')
          } else {
            _this.thirdPersonForm.doccard = ''
          }
          if (_this.thirdEvidenceList != null && _this.thirdEvidenceList.length > 0) {
            const uploadFile = []
            _this.thirdEvidenceList.forEach((item) => {
              uploadFile.push(item.uid)
            })
            _this.thirdPersonForm.thirdevidence = uploadFile.join(',')
          } else {
            _this.thirdPersonForm.thirdevidence = ''
          }
          // this.thirdPersonForm.id = nanoid();
          if (this.thirdPersonForm.birthym) {
            if (this.thirdPersonForm.birthym?.format) {
              this.thirdPersonForm.birthym = this.thirdPersonForm.birthym.format('YYYY-MM-DD')
            }
          }
          // 通过类型来重置部分值
          if (this.thirdPersonForm.type == Tp_applicantValue.CITIZEN) {
            this.thirdPersonForm.manager = undefined
            this.thirdPersonForm.job = undefined
            this.thirdPersonForm.doccardList = []
            this.thirdPersonForm.doccard = undefined
          } else {
            this.thirdPersonForm.nation = undefined
            this.thirdPersonForm.cardtype = undefined
            this.thirdPersonForm.birthym = undefined
            this.thirdPersonForm.gender = undefined
            this.thirdPersonForm.unit = undefined
            this.thirdPersonForm.filecardList = []
            this.thirdPersonForm.filecard = undefined
          }
          saveThirdPerson(this.thirdPersonForm).then((res) => {
            _this.loading = false
            if (res.code !== 0) {
              _this.$message.error('第三人保存失败')
            } else {
              _this.$message.success('保存成功')
              if (this.deleteFileList && this.deleteFileList.length > 0) {
                this.deleteFileList.forEach((fileId) => {
                  this.minioRemove(fileId)
                })
              }
              _this.$emit('reload')
              _this.onClose()
            }
          })
        } else {
          _this.loading = false
          // 加延时器的目的是为了vue实例更新未完成，我们可能获取DOM失败的问题
          // 利用原生js的方式，获取所有失败的类名，获得一个数组，取第一个元素获取焦点
          setTimeout(() => {
            const isError = document.getElementsByClassName('has-error')
            const input = isError[0].querySelector('input')
            // console.log(input)
            if (input !== null && input !== 'undefind' && input !== '') {
              isError[0].querySelector('input').focus()
                ? isError[0].querySelector('input').focus()
                : isError[0].querySelector('input').click()
            } else {
              isError[0].querySelector('textarea').focus()
            }
          }, 10)
          return false
        }
      })
    },
    // 第三人类型修改
    changePersonType () {
      if (this.thirdPersonForm.type == Tp_applicantValue.CITIZEN) {
        this.rules = {
          type: [{ required: true, message: '请选择类型', trigger: 'change' }],
          name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
          cardno: [{ validator: this.checkCardno }],
          tel: [{ validator: this.checkTel }],
          postcode: [{ validator: this.checkPostcode }]
        }
      } else {
        this.rules = {
          type: [{ required: true, message: '请选择类型', trigger: 'change' }],
          name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
          tel: [{ validator: this.checkTel }],
          postcode: [{ validator: this.checkPostcode }]
        }
      }
      this.$nextTick(() => {
        this.$refs.thirdPersonFormRef.validate()
      })
    }
  }
}
</script >

</script>

<style lang="less" scoped></style>
